import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import { ActionCreators } from "redux-undo";
import {
  copySelectedComponent,
  pasteCopiedComponent,
  removeSelectedComponent,
  selectNextComponent,
  selectPrevComponent,
} from "../store/componentsReducer";
import useGetPageInfo from "./useGetPageInfo";

function isActiveElementValid() {
  const activeElem = document.activeElement;

  // 当未聚焦任何元素时
  if (activeElem === document.body) return true;

  // 当聚焦于dnd-kit元素时
  if (activeElem?.matches('div[role="button"]')) return true;

  return false;
}

function useBindCanvasKeyPress() {
  const dispatch = useDispatch();
  const { isPublished } = useGetPageInfo();

  // 删除组件
  useKeyPress(["backspace", "delete"], () => {
    if (!isActiveElementValid() || isPublished) return;
    dispatch(removeSelectedComponent());
  });

  // 复制组件
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid() || isPublished) return;
    dispatch(copySelectedComponent());
  });

  // 粘贴组件
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementValid() || isPublished) return;
    dispatch(pasteCopiedComponent());
  });

  // 选中上一个组件
  useKeyPress("uparrow", () => {
    if (!isActiveElementValid() || isPublished) return;
    dispatch(selectPrevComponent());
  });

  // 选中下一个组件
  useKeyPress("downarrow", () => {
    if (!isActiveElementValid() || isPublished) return;
    dispatch(selectNextComponent());
  });

  // 撤销组件
  useKeyPress(
    ["ctrl.z", "meta.z"],
    () => {
      if (!isActiveElementValid() || isPublished) return;
      dispatch(ActionCreators.undo());
    },
    {
      // 精确匹配
      exactMatch: true,
    }
  );

  // 重做组件
  useKeyPress(["ctrl.shift.z", "meta.shift.z", "ctrl.y", "meta.y"], () => {
    if (!isActiveElementValid()) return;
    dispatch(ActionCreators.redo());
  });
}

export default useBindCanvasKeyPress;
